﻿using System;
using System.IO;
using System.Text;
using System.Xml.Serialization;

namespace WPRD.Common
{
    public class XmlFileTool
    {
        /// <summary>
        /// 序列化对象至Xml文档
        /// </summary>
        /// <param name="obj">对象</param>
        /// <param name="filePath">Xml文档路径</param>
        public static void SaveToXml(object obj, string filePath)
        {
            using (StreamWriter writer = new StreamWriter(filePath, false, Encoding.UTF8))
            {
                //初始化序列化配置
                XmlSerializer xmlSerializer = new XmlSerializer(obj.GetType());
                //序列化
                xmlSerializer.Serialize(writer, obj);
                writer.Close();
            }
        }

        /// <summary>
        /// 从Xml文档中反序列化对象
        /// </summary>
        /// <param name="type">对象类型</param>
        /// <param name="filePath">Xml文档路径</param>
        /// <returns></returns>
        public static object LoadFromXml(Type type, string filePath)
        {
            object obj;
            using (FileStream fileStream = new FileStream(filePath, FileMode.Open, FileAccess.Read))
            {
                //初始化序列化配置
                XmlSerializer xmlSerializer = new XmlSerializer(type);
                //反序列化
                obj = xmlSerializer.Deserialize(fileStream);
                fileStream.Close();
            }
            return obj;
        }
    }
}
